// 系统管理页面：流量监控、在线人数统计、日志管理
if (document.getElementById('trafficChart')) {
    // 流量监控
    var trafficChart = null;
    function fetchTrafficDataAndUpdateChart() {
        fetch('/api/system/traffic').then(res => res.json()).then(res => {
            if (res.success) {
                if (!trafficChart) {
                    trafficChart = echarts.init(document.getElementById('trafficChart'));
                    window.addEventListener('resize', () => trafficChart.resize());
                }
                // 直接使用后端返回的按天统计数据
                let x = res.data.x;
                let y = res.data.y;
                var option = {
                    title: { text: '流量监控（近30天）', left: 'center', textStyle: { color: '#1684FC', fontSize: 18 } },
                    tooltip: { trigger: 'axis', backgroundColor: '#fff', borderColor: '#1684FC', textStyle: { color: '#222' } },
                    grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
                    xAxis: {
                        type: 'category',
                        data: x,
                        axisLine: { lineStyle: { color: '#1684FC' } },
                        axisLabel: { color: '#333', fontWeight: 'bold', rotate: 45 }
                    },
                    yAxis: {
                        type: 'value',
                        axisLine: { lineStyle: { color: '#1684FC' } },
                        splitLine: { lineStyle: { color: '#eee' } },
                        axisLabel: { color: '#333' }
                    },
                    series: [{
                        name: '日访问量',
                        type: 'line',
                        smooth: true,
                        data: y,
                        areaStyle: { color: 'rgba(22,132,252,0.15)' },
                        lineStyle: { color: '#1684FC', width: 3 },
                        itemStyle: { color: '#1684FC' },
                        symbol: 'circle',
                        symbolSize: 8,
                        emphasis: { focus: 'series' },
                        label: { show: true, position: 'top', color: '#1684FC', fontWeight: 'bold' }
                    }]
                };
                trafficChart.setOption(option);
            }
        });
    }
    fetchTrafficDataAndUpdateChart();
    setInterval(fetchTrafficDataAndUpdateChart, 5000);
}
if (document.getElementById('onlineChart')) {
    // 在线人数统计
    var onlineChart = null;
    function fetchOnlineDataAndUpdateChart() {
        fetch('/api/system/online').then(res => res.json()).then(res => {
            if (res.success) {
                if (!onlineChart) {
                    onlineChart = echarts.init(document.getElementById('onlineChart'));
                    window.addEventListener('resize', () => onlineChart.resize());
                }
                var option = {
                    title: { text: '在线人数统计', left: 'center', textStyle: { color: '#28a745', fontSize: 18 } },
                    tooltip: { trigger: 'axis', backgroundColor: '#fff', borderColor: '#28a745', textStyle: { color: '#222' } },
                    grid: { left: '3%', right: '4%', bottom: '8%', containLabel: true },
                    xAxis: {
                        type: 'category',
                        data: res.data.x,
                        axisLine: { lineStyle: { color: '#28a745' } },
                        axisLabel: { color: '#333', fontWeight: 'bold' }
                    },
                    yAxis: {
                        type: 'value',
                        axisLine: { lineStyle: { color: '#28a745' } },
                        splitLine: { lineStyle: { color: '#eee' } },
                        axisLabel: { color: '#333' }
                    },
                    series: [{
                        name: '在线人数',
                        type: 'bar',
                        data: res.data.y,
                        barWidth: 40,
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#43e97b' },
                                { offset: 1, color: '#38f9d7' }
                            ])
                        },
                        label: { show: true, position: 'top', color: '#28a745', fontWeight: 'bold' },
                        emphasis: { focus: 'series' },
                        animationDuration: 800
                    }]
                };
                onlineChart.setOption(option);
            }
        });
    }
    fetchOnlineDataAndUpdateChart();
    setInterval(fetchOnlineDataAndUpdateChart, 5000);
}
if (document.getElementById('logList')) {
    // 日志表格渲染
    function renderLogTable(logs) {
        if (!logs || logs.length === 0) {
            return '<div class="no-logs">暂无日志</div>';
        }
        let html = '<table class="log-table"><thead><tr>' +
            '<th>时间</th><th>级别</th><th>用户</th><th>操作</th><th>内容</th><th>IP</th></tr></thead><tbody>';
        for (const log of logs) {
            html += `<tr>
                <td>${log.timestamp || ''}</td>
                <td>${log.level || ''}</td>
                <td>${log.username || ''}</td>
                <td>${log.action || ''}</td>
                <td>${log.message || ''}</td>
                <td>${log.ip || ''}</td>
            </tr>`;
        }
        html += '</tbody></table>';
        return html;
    }

    // 加载日志（分页可扩展）
    function loadLogs() {
        fetch('/api/system/logs?page=1&page_size=50').then(res => res.json()).then(res => {
            if (res.success) {
                document.getElementById('logList').innerHTML = renderLogTable(res.logs);
            } else {
                document.getElementById('logList').innerHTML = '<div class="no-logs">日志加载失败</div>';
            }
        });
    }
    // 清空日志
    function clearLogs() {
        fetch('/api/system/logs', { method: 'DELETE' }).then(res => res.json()).then(res => {
            if (res.success) loadLogs();
        });
    }
    // 导出日志仅下载
    function exportLogs() {
        const a = document.createElement('a');
        a.href = '/api/system/logs/export';
        a.download = 'system.log';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
    // 绑定按钮事件
    if (document.getElementById('loadLogsBtn'))
        document.getElementById('loadLogsBtn').onclick = loadLogs;
    if (document.getElementById('clearLogsBtn'))
        document.getElementById('clearLogsBtn').onclick = clearLogs;
    if (document.getElementById('exportLogsBtn'))
        document.getElementById('exportLogsBtn').onclick = exportLogs;
    // 页面加载自动加载日志
    loadLogs();
} 
// 退出登录功能
async function logout() {
    try {
        const response = await fetch('/api/logout', {
            method: 'POST',
            credentials: 'include'
        });

        const data = await response.json();

        if (data.redirect) {
            window.location.href = data.redirect;
        }
    } catch (error) {
        console.error('退出登录错误:', error);
        window.location.href = '/login';
    }
}

// 页面加载完成后设置事件监听器
document.addEventListener('DOMContentLoaded', function() {
    // 绑定退出登录事件
    const exitButton = document.querySelector('.exit');
    if (exitButton) {
        exitButton.addEventListener('click', logout);
    }
});

// 全局反馈管理函数
// 查看反馈详情
function viewFeedback(feedbackId) {
    // 获取反馈详情
    fetch(`/api/feedback/admin/detail/${feedbackId}`, { credentials: 'include' })
        .then(response => response.json())
        .then(feedback => {
            if (feedback.error) {
                alert('获取反馈详情失败: ' + feedback.error);
                return;
            }

            // 渲染反馈详情
            const detailContent = document.getElementById('feedbackDetailContent');
            detailContent.innerHTML = renderFeedbackDetail(feedback);

            // 显示回复按钮（如果状态为待处理）
            const respondBtn = document.getElementById('respondBtn');
            if (feedback.status === 'pending') {
                respondBtn.style.display = 'inline-block';
                respondBtn.onclick = () => showRespondForm(feedbackId);
            } else {
                respondBtn.style.display = 'none';
            }

            // 显示模态框
            document.getElementById('feedbackDetailModal').style.display = 'flex';
        })
        .catch(error => {
            console.error('获取反馈详情失败:', error);
            alert('获取反馈详情失败，请稍后重试');
        });
}

// 渲染反馈详情
function renderFeedbackDetail(feedback) {
    const typeLabels = {
        'bug': '问题反馈',
        'feature': '功能建议',
        'improvement': '改进建议',
        'other': '其他'
    };

    const statusLabels = {
        'pending': '待处理',
        'responded': '已回复'
    };

    const statusClass = feedback.status === 'responded' ? 'responded' : 'pending';

    return `
        <div class="feedback-detail">
            <div class="detail-item">
                <span class="detail-label">反馈ID：</span>
                <div class="detail-value">${feedback.id}</div>
            </div>
            <div class="detail-item">
                <span class="detail-label">提交用户：</span>
                <div class="detail-value">${feedback.username}</div>
            </div>
            <div class="detail-item">
                <span class="detail-label">反馈类型：</span>
                <div class="detail-value">${typeLabels[feedback.feedback_type] || feedback.feedback_type}</div>
            </div>
            <div class="detail-item">
                <span class="detail-label">标题：</span>
                <div class="detail-value">${feedback.title}</div>
            </div>
            <div class="detail-item">
                <span class="detail-label">详细内容：</span>
                <div class="detail-value detail-content">${feedback.content}</div>
            </div>
            <div class="detail-item">
                <span class="detail-label">提交时间：</span>
                <div class="detail-value">${feedback.created_at}</div>
            </div>
            <div class="detail-item">
                <span class="detail-label">状态：</span>
                <div class="detail-value">
                    <span class="status ${statusClass}">${statusLabels[feedback.status] || feedback.status}</span>
                </div>
            </div>
            ${feedback.updated_at ? `
            <div class="detail-item">
                <span class="detail-label">更新时间：</span>
                <div class="detail-value">${feedback.updated_at}</div>
            </div>
            ` : ''}
            ${feedback.admin_response ? `
            <div class="detail-item">
                <div class="admin-response">
                    <h4>管理员回复：</h4>
                    <div class="detail-content">${feedback.admin_response}</div>
                </div>
            </div>
            ` : ''}
        </div>
    `;
}

// 回复反馈（从表格直接回复）
function respondToFeedback(feedbackId) {
    showRespondForm(feedbackId);
}

// 显示回复表单
function showRespondForm(feedbackId) {
    // 关闭详情模态框
    closeFeedbackDetailModal();

    // 清空回复内容
    document.getElementById('respondContent').value = '';

    // 存储当前反馈ID
    window.currentFeedbackId = feedbackId;

    // 显示回复模态框
    document.getElementById('respondModal').style.display = 'flex';
}

// 提交回复
function submitResponse() {
    const feedbackId = window.currentFeedbackId;
    const response = document.getElementById('respondContent').value.trim();

    if (!response) {
        alert('请输入回复内容');
        return;
    }

    fetch('/api/feedback/admin/respond', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            feedback_id: feedbackId,
            admin_response: response
        })
    }).then(res => res.json()).then(res => {
        if (res.success) {
            alert('回复成功！');
            closeRespondModal();
            loadFeedbacks(); // 重新加载反馈列表
        } else {
            alert('回复失败: ' + (res.error || '未知错误'));
        }
    }).catch(error => {
        console.error('回复反馈失败:', error);
        alert('回复失败，请稍后重试');
    });
}

// 关闭反馈详情模态框
function closeFeedbackDetailModal() {
    document.getElementById('feedbackDetailModal').style.display = 'none';
}

// 关闭回复模态框
function closeRespondModal() {
    document.getElementById('respondModal').style.display = 'none';
    document.getElementById('respondContent').value = '';
    window.currentFeedbackId = null;
}

// 用户反馈管理功能
if (document.getElementById('feedbackList')) {
    // 反馈表格渲染
    function renderFeedbackTable(feedbacks) {
        if (!feedbacks || feedbacks.length === 0) {
            return '<div class="no-feedback">暂无反馈</div>';
        }

        let html = '<table class="feedback-table"><thead><tr>' +
            '<th>时间</th><th>用户</th><th>类型</th><th>标题</th><th>内容</th><th>状态</th><th>操作</th></tr></thead><tbody>';

        for (const feedback of feedbacks) {
            const statusClass = feedback.status === 'responded' ? 'responded' : 'pending';
            const statusText = feedback.status === 'responded' ? '已回复' : '待处理';

            html += `<tr>
                <td>${feedback.created_at || ''}</td>
                <td>${feedback.username || ''}</td>
                <td>${getFeedbackTypeLabel(feedback.feedback_type)}</td>
                <td>${feedback.title || ''}</td>
                <td>${feedback.content || ''}</td>
                <td><span class="status ${statusClass}">${statusText}</span></td>
                <td>
                    <button onclick="viewFeedback(${feedback.id})" class="btn-view">查看</button>
                    ${feedback.status === 'pending' ? `<button onclick="respondToFeedback(${feedback.id})" class="btn-respond">回复</button>` : ''}
                </td>
            </tr>`;
        }
        html += '</tbody></table>';
        return html;
    }

    // 获取反馈类型标签
    function getFeedbackTypeLabel(type) {
        const typeLabels = {
            'bug': '问题反馈',
            'feature': '功能建议',
            'improvement': '改进建议',
            'other': '其他'
        };
        return typeLabels[type] || type;
    }

    // 加载反馈列表
    function loadFeedbacks() {
        fetch('/api/feedback/admin/list', { credentials: 'include' }).then(res => res.json()).then(res => {
            if (res.success !== false) {
                document.getElementById('feedbackList').innerHTML = renderFeedbackTable(res);
            } else {
                document.getElementById('feedbackList').innerHTML = '<div class="no-feedback">反馈加载失败</div>';
            }
        }).catch(error => {
            console.error('加载反馈失败:', error);
            document.getElementById('feedbackList').innerHTML = '<div class="no-feedback">反馈加载失败</div>';
        });
    }

    // 查看反馈详情
    function viewFeedback(feedbackId) {
        // 获取反馈详情
        fetch(`/api/feedback/admin/detail/${feedbackId}`, { credentials: 'include' })
            .then(response => response.json())
            .then(feedback => {
                if (feedback.error) {
                    alert('获取反馈详情失败: ' + feedback.error);
                    return;
                }

                // 渲染反馈详情
                const detailContent = document.getElementById('feedbackDetailContent');
                detailContent.innerHTML = renderFeedbackDetail(feedback);

                // 显示回复按钮（如果状态为待处理）
                const respondBtn = document.getElementById('respondBtn');
                if (feedback.status === 'pending') {
                    respondBtn.style.display = 'inline-block';
                    respondBtn.onclick = () => showRespondForm(feedbackId);
                } else {
                    respondBtn.style.display = 'none';
                }

                // 显示模态框
                document.getElementById('feedbackDetailModal').style.display = 'flex';
            })
            .catch(error => {
                console.error('获取反馈详情失败:', error);
                alert('获取反馈详情失败，请稍后重试');
            });
    }

    // 渲染反馈详情
    function renderFeedbackDetail(feedback) {
        const typeLabels = {
            'bug': '问题反馈',
            'feature': '功能建议',
            'improvement': '改进建议',
            'other': '其他'
        };

        const statusLabels = {
            'pending': '待处理',
            'responded': '已回复'
        };

        const statusClass = feedback.status === 'responded' ? 'responded' : 'pending';

        return `
            <div class="feedback-detail">
                <div class="detail-item">
                    <span class="detail-label">反馈ID：</span>
                    <div class="detail-value">${feedback.id}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">提交用户：</span>
                    <div class="detail-value">${feedback.username}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">反馈类型：</span>
                    <div class="detail-value">${typeLabels[feedback.feedback_type] || feedback.feedback_type}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">标题：</span>
                    <div class="detail-value">${feedback.title}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">详细内容：</span>
                    <div class="detail-value detail-content">${feedback.content}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">提交时间：</span>
                    <div class="detail-value">${feedback.created_at}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">状态：</span>
                    <div class="detail-value">
                        <span class="status ${statusClass}">${statusLabels[feedback.status] || feedback.status}</span>
                    </div>
                </div>
                ${feedback.updated_at ? `
                <div class="detail-item">
                    <span class="detail-label">更新时间：</span>
                    <div class="detail-value">${feedback.updated_at}</div>
                </div>
                ` : ''}
                ${feedback.admin_response ? `
                <div class="detail-item">
                    <div class="admin-response">
                        <h4>管理员回复：</h4>
                        <div class="detail-content">${feedback.admin_response}</div>
                    </div>
                </div>
                ` : ''}
            </div>
        `;
    }

    // 回复反馈（从表格直接回复）
    function respondToFeedback(feedbackId) {
        showRespondForm(feedbackId);
    }

    // 显示回复表单
    function showRespondForm(feedbackId) {
        // 关闭详情模态框
        closeFeedbackDetailModal();

        // 清空回复内容
        document.getElementById('respondContent').value = '';

        // 存储当前反馈ID
        window.currentFeedbackId = feedbackId;

        // 显示回复模态框
        document.getElementById('respondModal').style.display = 'flex';
    }

    // 提交回复
    function submitResponse() {
        const feedbackId = window.currentFeedbackId;
        const response = document.getElementById('respondContent').value.trim();

        if (!response) {
            alert('请输入回复内容');
            return;
        }

        fetch('/api/feedback/admin/respond', {
            method: 'POST',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                feedback_id: feedbackId,
                admin_response: response
            })
        }).then(res => res.json()).then(res => {
            if (res.success) {
                alert('回复成功！');
                closeRespondModal();
                loadFeedbacks(); // 重新加载反馈列表
            } else {
                alert('回复失败: ' + (res.error || '未知错误'));
            }
        }).catch(error => {
            console.error('回复反馈失败:', error);
            alert('回复失败，请稍后重试');
        });
    }

    // 关闭反馈详情模态框
    function closeFeedbackDetailModal() {
        document.getElementById('feedbackDetailModal').style.display = 'none';
    }

    // 关闭回复模态框
    function closeRespondModal() {
        document.getElementById('respondModal').style.display = 'none';
        document.getElementById('respondContent').value = '';
        window.currentFeedbackId = null;
    }

    // 绑定按钮事件
    if (document.getElementById('loadFeedbackBtn')) {
        document.getElementById('loadFeedbackBtn').onclick = loadFeedbacks;
    }

    // 页面加载自动加载反馈
    loadFeedbacks();

    // 定期刷新反馈列表
    setInterval(loadFeedbacks, 30000); // 每30秒刷新一次

    // 添加模态框点击外部关闭功能
    setupModalCloseHandlers();
}

// 设置模态框关闭处理
function setupModalCloseHandlers() {
    // 反馈详情模态框
    const feedbackDetailModal = document.getElementById('feedbackDetailModal');
    feedbackDetailModal.addEventListener('click', function(e) {
        if (e.target === this) {
            closeFeedbackDetailModal();
        }
    });

    // 回复模态框
    const respondModal = document.getElementById('respondModal');
    respondModal.addEventListener('click', function(e) {
        if (e.target === this) {
            closeRespondModal();
        }
    });

    // 添加ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            if (feedbackDetailModal.style.display === 'flex') {
                closeFeedbackDetailModal();
            }
            if (respondModal.style.display === 'flex') {
                closeRespondModal();
            }
        }
    });
}